<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改发布产品信息')" />
    <th:block th:include="include :: summernote-css" />
    <th:block th:include="include :: jasny-bootstrap-css" />
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-publish-edit" th:object="${jtProductPublish}">
        <h4 class="form-header h4">[[#{productRelease}]]</h4>
        <input name="productId" th:field="*{productId}" type="hidden">
        <input name="removeSkuIds" type="hidden">
        <div class="rows">
            <div class="col-xs-6">
                <label class="col-sm-4 control-label is-required">[[#{image}]]：</label>
                <div class="form-group">
                    <div class="fileinput fileinput-new" data-provides="fileinput">
                        <div class="fileinput-new thumbnail" style="width: 120px;">
                            <img th:src="*{imageUrl}" >
                        </div>
                        <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 450px;"></div>
                        <div>
                            <span class="btn btn-white btn-file"><span class="fileinput-new">[[#{select.img}]]</span><span class="fileinput-exists">[[#{change}]]</span>
                            <input type="file" id="img-file" accept="image/*"></span>
                            <a href="#" class="btn btn-white fileinput-exists" data-dismiss="fileinput">[[#{clear}]]</a>
                        </div>
                        <span class="help-block m-b-none"><i class="fa fa-info-circle"></i>[[#{suggest.img.size}]]</span>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">[[#{productTitle}]]：</label>
                    <div class="col-sm-8">
                        <input name="productTitle" th:field="*{productTitle}" class="form-control" type="text" required>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">[[#{productAbbreviation}]]：</label>
                    <div class="col-sm-8">
                        <input name="productSimpleName" th:field="*{productSimpleName}" class="form-control" type="text">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">[[#{spu}]]：</label>
                    <div class="col-sm-8">
                        <input name="styleNo" th:field="*{styleNo}" class="form-control" type="text" required>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">[[#{releaseRegion}]]：</label>
                    <div class="col-sm-8">
                        <input name="publishRegion" th:field="*{publishRegion}" class="form-control" type="hidden">

                        <select name="publishCountryCode" th:field="*{publishCountryCode}" class="form-control" required>
                            <option value="">-请选择-</option>
                            <option th:each="region : ${publishRegionList}" th:value="${region.countryCode}" th:text="${region.countryRegion}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">[[#{currency}]]：</label>
                    <div class="col-sm-8">
                        <input name="currency" th:field="*{currency}" class="form-control" type="text" required>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">[[#{sellingPrice}]]：</label>
                    <div class="col-sm-8">
                        <input name="salePrice" th:field="*{salePrice}" class="form-control" type="number" required>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">[[#{marketPrice}]]：</label>
                    <div class="col-sm-8">
                        <input name="marketPrice" th:field="*{marketPrice}" class="form-control" type="number">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">[[#{product.category}]]：</label>
                    <div class="col-sm-8">
                        <select name="categoryId" th:field="*{categoryId}" class="form-control">
                            <option value="">-请选择-</option>
                            <option th:each="category : ${categoryList}" th:value="${category.categoryId}" th:text="${category.categoryNameZh}"></option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">[[#{status}]]：</label>
                    <div class="col-sm-8">
                        <div class="radio-box" th:each="dict : ${@dict.getType('jt_product_status')}">
                            <input type="radio" th:id="${'status_' + dict.dictCode}" name="status" th:value="${dict.dictValue}" th:field="*{status}">
                            <label th:for="${'status_' + dict.dictCode}" th:text="${dict.dictLabel}"></label>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-2 control-label">[[#{productDetails}]]：</label>
                    <div class="col-sm-10">
                        <input id="details" name="details" th:field="*{details}" class="form-control" type="hidden"/>
                        <div class="summernote"></div>
                    </div>
                </div>
            </div>
        </div>

        <h4 class="form-header h4" th:text="#{skuInfo}">产品SKU信息</h4>
        <div class="row">
            <div class="col-sm-12">
                <button type="button" class="btn btn-white btn-sm" onclick="selectProductToParentCallBack()"><i class="fa fa-plus"> [[#{add}]]</i></button>
                <button type="button" class="btn btn-white btn-sm" onclick="subDelRow()"><i class="fa fa-minus"> [[#{delete}]]</i></button>
                <div class="col-sm-12 select-table table-striped">
                    <table id="bootstrap-table"></table>
                </div>
            </div>
        </div>

        <div class="toolbar toolbar-bottom" role="toolbar" style="text-align: right;">
            <a class="btn btn-primary btn-rounded btn-sm" onclick="submitHandler()"><i class="fa fa-search"></i>&nbsp;[[#{sure}]]</a><!-- 确定 -->
        </div>
    </form>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: summernote-js" />
<th:block th:include="include :: jasny-bootstrap-js" />
<script th:inline="javascript">
    var prefix = ctx + "business/publish";
    var statusDatas = [[${@dict.getType('sys_normal_disable')}]];
    var attributesDatas = [[${@dict.getType('jt_product_attributes')}]];

    $("#form-pulish-edit").validate({
        focusCleanup: true
    });

    function submitHandler() {
        if ($.validate.form()) {
            //$.operate.save(prefix + "/edit", $('#form-publish-edit').serialize());

            var sHtml = $('.summernote').summernote('code');
            $("#details").val(sHtml);

            submitData(prefix + "/edit", $('#form-publish-edit').serializeObject());
        }
    }

    function submitData(url, formData) {
        var file = $('#img-file')[0].files[0];

        if (file != undefined) {
            $.modal.alertWarning(i18n('select.img'));
            var fileSize = parseInt(file.size / 1024); //KB
            if (fileSize > 1024 * 5) {
                var sizeTips = i18n('select.img.size');
                $.modal.alertWarning(sizeTips.replace("{0}", fileSize));
                return;
            }
        }

        formData.append('file', file);

        $.ajax({
            url: url,
            type: 'post',
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function(result) {
                //提交后不刷新清空；
                if (result && result.code == 0) {
                    $.modal.msgSuccess(result.msg);
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        });
    }

    $.fn.serializeObject = function()
    {
        var o = new FormData();
        var formArray = this.serializeArray();
        $.each(formArray, function() {
            o.append(this.name+'', (this.value || ''));
        });
        return o;
    };

    function initSummerNote() {
        $('.summernote').summernote({
            placeholder: i18n('inputProductDetails'),
            height: 292,
            lang: 'zh-CN',
            followingToolbar: false,
            dialogsInBody: true,
            callbacks: {
                onImageUpload: function (files) {
                    sendFile(files[0], this);
                }
            }
        });
        var content = $("#details").val();
        $('.summernote').summernote('code', content);

    }

    // 上传文件
    function sendFile(file, obj) {
        var data = new FormData();
        data.append("file", file);
        $.ajax({
            type: "POST",
            url: prefix + "/upload/image",
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(result) {
                if (result.code == web_status.SUCCESS) {
                    $(obj).summernote('editor.insertImage', result.fileName, result.fileName);
                } else {
                    $.modal.alertError(result.msg);
                }
            },
            error: function(error) {
                $.modal.alertWarning(i18n("imageUploadFailed"));
            }
        });
    }

    $(function() {
        initSummerNote();

        var options = {
            data: [[${jtProductPublish.jtProductPublishSkuList}]],
            pagination: false,
            showSearch: false,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            sidePagination: "client",
            uniqueId:"index",
            columns: [{
                checkbox: true
            },
                {
                    field: 'index',
                    align: 'center',
                    title: i18n('serialNumber'),
                    formatter: function (value, row, index) {
                        var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index));
                        return columnIndex + $.table.serialNumber(index);
                    }
                },
                {
                    field: 'imageUrl',
                    align: 'center',
                    title: i18n('image'),
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='hidden' name='jtProductPublishSkuList[%s].imageUrl' value='%s'>", index, value);
                        var imageUrl = value;
                        if(ctx.length > 1 && imageUrl != ""){
                            if(imageUrl.indexOf("/") == 0){
                                imageUrl = ctx + imageUrl.substr(1);
                            } else {
                                imageUrl = ctx + imageUrl;
                            }
                        }
                        return imageLazyLoadView(imageUrl, "auto", 750) + html;
                    }
                },
                {
                    field: 'skuName',
                    align: 'center',
                    title: i18n('productName'),
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='jtProductPublishSkuList[%s].skuName' value='%s'>", index, value);
                        html += $.common.sprintf("<input class='form-control' type='hidden' name='jtProductPublishSkuList[%s].productId' value='%s'>", index, row.productId);
                        html += $.common.sprintf("<input class='form-control' type='hidden' name='jtProductPublishSkuList[%s].skuId' value='%s'>", index, row.skuId);
                        return html;
                    }
                },
                {
                    field: 'skuCode',
                    align: 'center',
                    title: i18n('sku'),
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='jtProductPublishSkuList[%s].skuCode' value='%s'>", index, value);
                        return html;
                    }
                },
                {
                    field: 'attributes',
                    align: 'center',
                    title: i18n('attributes'),
                    formatter: function(value, row, index) {
                        var name = $.common.sprintf("jtProductPublishSkuList[%s].attributes", index);
                        return $.common.dictToSelect(attributesDatas, value, name);
                    }
                },
                {
                    field: 'weight',
                    align: 'center',
                    title: i18n('weight')+'(KG)',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='jtProductPublishSkuList[%s].weight' value='%s'>", index, value);
                        return html;
                    }
                },

                {
                    field: 'unit',
                    align: 'center',
                    title: i18n('unit'),
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='jtProductPublishSkuList[%s].unit' value='%s'>", index, value);
                        return html;
                    }
                },
                {
                    field: 'salePrice',
                    align: 'center',
                    title: i18n('sellingPrice'),
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='number' name='jtProductPublishSkuList[%s].salePrice' value='%s' required>", index, value);
                        return html;
                    }
                },
                {
                    field: 'spec',
                    align: 'center',
                    title: i18n('spec'),
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='jtProductPublishSkuList[%s].spec' value='%s'>", index, value);
                        return html;
                    }
                },

                {
                    field: 'countryOfOrigin',
                    align: 'center',
                    title: i18n('countryOfOrigin'),
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='jtProductPublishSkuList[%s].countryOfOrigin' value='%s'>", index, value);
                        return html;
                    }
                },
                {
                    field: 'soldQty',
                    align: 'center',
                    title: i18n('soldQty'),
                    formatter: function(value, row, index) {
                        return value;
                    }
                },
                {
                    field: 'stock',
                    align: 'center',
                    title: i18n('stock'),
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='jtProductPublishSkuList[%s].stock' value='%s'>", index, value);
                        return html;
                    }
                },
                {
                    field: 'status',
                    align: 'center',
                    width:'100px',
                    title: i18n('status'),
                    formatter: function(value, row, index) {
                        var name = $.common.sprintf("jtProductPublishSkuList[%s].status", index);
                        return $.common.dictToSelect(statusDatas, value, name);
                    }
                },
                {
                    title: i18n('operate'),
                    align: 'center',
                    formatter: function(value, row, index) {
                        var value = $.common.isNotEmpty(row.index) ? row.index : $.table.serialNumber(index);

                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="doChange(' + index + ',\'' + row.skuId + '\')"><i class="fa fa-edit"></i> '+i18n('edit')+'</a> ');
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="delRow(\'' + value + '\',\''+row.skuId+'\')"><i class="fa fa-remove"></i>'+i18n('delete')+'</a>');
                        return actions.join('');

                    }
                }]
        };
        $.table.init(options);
    });

    // 图片预览
    function imageLazyLoadView(value, height, width, target) {
        if ($.common.isEmpty(width)) {
            width = 'auto';
        }
        if ($.common.isEmpty(height)) {
            height = 'auto';
        }
        if($.common.isMobile()){
            target = "blank";
        }
        var windowWidth = $(window).width();
        //console.log("imgW====="+windowWidth)
        var imgW = 'img-md';
        if(windowWidth < 1024){
            imgW = 'img-lg';
        }
        // blank or self
        var _target = $.common.isEmpty(target) ? 'self' : target;
        if ($.common.isNotEmpty(value)) {
            return $.common.sprintf("<img class='img-circle "+imgW+" lazyload' data-type='2' data-height='%s' data-width='%s' data-target='%s' src='%s' />", height, width, _target, value);
        } else {
            return $.common.nullToStr(value);
        }
    }

    function subDelRow() {
        var skuIds = $.table.selectColumns("skuId");
        var removeSkuIds = $("input[name='removeSkuIds']").val();

        if(skuIds){
            removeSkuIds += skuIds +",";
        }

        $("input[name='removeSkuIds']").val(removeSkuIds);

        sub.delRow()
    }

    function delRow(val, skuId) {
        var removeSkuIds = $("input[name='removeSkuIds']").val();

        if(skuId != null){
            removeSkuIds += skuId +",";
        }

        $("input[name='removeSkuIds']").val(removeSkuIds);

        sub.delRowByIndex(val);
    }

    function addRow(productInfo) {
        var count = $("#" + table.options.id).bootstrapTable('getData').length;
        var row = {
            index: $.table.serialNumber(count),
            skuName: productInfo.productName,
            skuCode: productInfo.productCode,
            attributes: productInfo.attributes,
            weight: productInfo.weight,
            unit: productInfo.unit,
            salePrice: "",
            imageUrl: productInfo.imageUrl,
            spec: productInfo.spec,
            countryOfOrigin: productInfo.countryOfOrigin,
            stock: "",
            status: 0,
        }
        sub.addRow(row);
    }

    $("select[name='publishCountryCode']").bind("change", function() {
        var publishRegion = $(this).find("option:selected").text();
        var currency = $(this).find("option:selected").attr("currency");
        console.log(publishRegion);
        console.log("==="+currency);
        $("input[name='publishRegion']").val(publishRegion);
        $("input[name='currency']").val(currency);
    });

    var productPrefix = ctx + "business/product";
    // callBack获取父窗口方法
    function selectProductToParentCallBack(){
        var options = {
            title: i18n('selectProduct'),
            url: productPrefix + "/select",
            callBack: doSubmit2
        };
        $.modal.openOptions(options);
    }

    function doSubmit2(index, layero){
        var selectedRow = layero.find("iframe")[0].contentWindow.getSelections();
        if (selectedRow.length == 0) {
            $.modal.alertWarning(i18n('selectOneProduct'));
            return;
        }

        selectedRow.forEach(function(row) {
            addRow(row);
        });

        $.modal.close(index);
    }

    var indexVal;
    function doChange(idx, skuId){
        indexVal = idx;
        var productPrefix = ctx + "business/product";
        var options = {
            title: i18n('selectProduct'),
            url: productPrefix + "/select",
            callBack: doSubmit3
        };
        $.modal.openOptions(options);
    }


    function doSubmit3(index, layero){
        var selectedRow = layero.find("iframe")[0].contentWindow.getSelections();
        if (selectedRow.length == 0) {
            $.modal.alertWarning(i18n('selectOneProduct'));
            return;
        }
        if(selectedRow.length > 1){
            $.modal.alertWarning(i18n('selectOneProduct'));
            return;
        }

        selectedRow.forEach(function(row) {
            updateRow(indexVal, row);
        });

        $.modal.close(index);
    }

    function updateRow(rowIndex, productInfo) {
        var data = $("#" + table.options.id).bootstrapTable('getData')[rowIndex];
        var rowData = {
            skuId: data.skuId,
            productId: data.productId,
            skuName: productInfo.productName,
            skuCode: productInfo.productCode,
            attributes: productInfo.attributes,
            weight: productInfo.weight,
            unit: productInfo.unit,
            salePrice: data.salePrice,
            imageUrl: productInfo.imageUrl,
            spec: productInfo.spec,
            countryOfOrigin: productInfo.countryOfOrigin,
            stock: data.stock,
            status: data.status,
        }
        $("#bootstrap-table").bootstrapTable("updateRow", { index: rowIndex, row: rowData });
    }
</script>
<script th:inline="javascript">
    var ROOT = [[${#servletContext.contextPath}]];
    var LANG_COUNTRY = [[${#locale.language+'_'+#locale.country}]];

    //初始化i18n
    $.i18n.properties({
        path: ROOT + '/i18n/',//这里表示访问路径
        name: 'messages',//文件名开头
        language: LANG_COUNTRY,//文件名语言 例如en_US
        mode: 'map'//默认值
    });

    //i18n函数
    function i18n(msgKey) {
        try {
            return $.i18n.prop(msgKey);
        } catch (e) {
            return msgKey;
        }
    }
</script>

</body>
</html>